package com.seal.tsms.school.controller;

import com.seal.tsms.base.controller.BaseController;
import com.seal.tsms.base.dao.Pagination;
import com.seal.tsms.base.service.BaseService;
import com.seal.tsms.school.entity.StudentInfo;
import com.seal.tsms.school.entity.StudentRecord;
import com.seal.tsms.school.service.StudentRecordService;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * Created by zhaishuai on 2016/1/22.
 */
@Controller
@RequestMapping("/school/studentRecord")//相当于struts2 的namespace属性
public class StudentRecordController extends BaseController<StudentRecord,String>{
    @Autowired
    @Qualifier("studentRecordServiceImpl")
    @Override
    public void setSelfService(BaseService<StudentRecord, String> selfService) {
        super.setSelfService(selfService);
    }
    @RequestMapping(value = "/new" ,method = RequestMethod.GET)
    public String create(){ return "school/studentRecord/addStudentRecord"; }
    @RequestMapping(value = "/new",method = RequestMethod.POST)
    public String save(@ModelAttribute("studentRecord")StudentRecord studentRecord, RedirectAttributes attr){
        StudentInfo studentInfo=new StudentInfo();
        studentInfo.setId("a");
        studentRecord.setStudentInfo(studentInfo);
        getSelfService().save(studentRecord);
        attr.addAttribute("id",studentRecord.getId());
        attr.addFlashAttribute("message","一条记录添加成功");
        return "redirect:/school/studentRecord/show.do";
    }
    @RequestMapping(value="/show")
    public String show(@RequestParam String id, ModelMap model){
        model.addAttribute("studentRecord",getSelfService().get(id));
        return "school/studentRecords/show";
    }

    @RequestMapping(value = "/importxls",method = RequestMethod.GET)
    public String toImportxls(){
        return "school/studentRecord/import";
    }
    @RequestMapping(value = "/importxls",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> importxls(@RequestParam(value = "file")MultipartFile file, HttpServletRequest request,RedirectAttributes attr){

        Map<String,Object> data=new HashMap<String,Object>();
        String path=request.getServletContext().getRealPath("/static/xls");
       // log.debug(path+"..");
        String fileName=file.getOriginalFilename();
        File targetFile=new File(path,fileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        try{

            file.transferTo(targetFile);
            //log.debug(targetFile.length());
            InputStream inputXML = new BufferedInputStream(getClass().getResourceAsStream("/xml/xls-template/studentrecord.xml"));
            XLSReader mainReader = ReaderBuilder.buildFromXML( inputXML );
            InputStream inputXLS = new BufferedInputStream(new FileInputStream(targetFile));


            List<StudentRecord> studentrecords = new ArrayList<StudentRecord>();
            Map beans = new HashMap();

            beans.put("studentrecords", studentrecords);
            ReaderConfig.getInstance().setSkipErrors( true );
            ReaderConfig.getInstance().setUseDefaultValuesForPrimitiveTypes( true );
            XLSReadStatus readStatus = mainReader.read( inputXLS, beans);
            //log.debug(beans.get("studentrecords").toString());
           // for (StudentRecord sr:departments) {
                //log.debug(sr.getRecordNum()+);
               // System.out.println(sr.getRecordNum()+"\t"+sr.getStudentInfo().getStudent_name()+"\t"+sr.getStudentInfo().getRelationInfo().getAddress());
            //  this.getSelfService().save(sr);
           // }
            ((StudentRecordService)getSelfService()).saveList(studentrecords);



            //attr.addFlashAttribute("msg","导入成功!");
            data.put("success",true);
            data.put("msg","成功导入"+studentrecords.size()+"条记录");

        }catch (Exception e){
            //attr.addFlashAttribute("msg","导入失败!");
            //log.error("导入失败",e);
            data.put("success",false);
            data.put("msg","导入失败："+e.getMessage());
        }finally {
            if (targetFile.isFile() && targetFile.exists()) {
                targetFile.delete();

            }
        }



        return data;

    }

    @RequestMapping(value = "/ok")
    public String ok(){
        return "school/studentRecord/ok";
    }
    @RequestMapping(value = "/exportXls")
    public ResponseEntity<FileSystemResource> exportXls(){
        InputStream is =null;
        FileOutputStream os =null;
        try{
            List<StudentRecord> studentRecords= (List<StudentRecord>) getSelfService().list(DetachedCriteria.forClass(StudentRecord.class),null);
            is = getClass().getResourceAsStream("/xml/xls-template/studentrecord-temp.xls");

            File file=new File("d:/git/"+System.currentTimeMillis()+".xls");
            os = new FileOutputStream(file);
            //os=new PipedOutputStream();
            //PipedInputStream bin=new PipedInputStream(os);

            Context context = new Context();
            context.putVar("studentRecords", studentRecords);
            JxlsHelper.getInstance().processTemplateAtCell(is, os, context, "学员档案!A1");
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
            headers.add("Content-Disposition", "attachment; filename=" + URLEncoder.encode("学员档案.xls", "UTF-8"));
            return new ResponseEntity<FileSystemResource>(new FileSystemResource(file),headers, HttpStatus.OK);

        }catch (Exception e){
            log.error("error",e);
            //attr.addFlashAttribute("msg","导出失败");
        }finally {
            try {
                os.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
        //return "redirect:/school/studentRecord/ok.do";
    }
    @RequestMapping(value = "/exportXlsByParam")
    public void exportXls(String name,String value, HttpServletResponse response){
        try(InputStream is=getClass().getResourceAsStream("/xml/xls-template/studentrecord-temp.xls")){
           // DetachedCriteria dc=DetachedCriteria.forClass(StudentRecord.class);
           // if(!"all".equals(name)&&name!=null) {
           //     dc.add(name)
           // }
            Map p=new HashMap();
            if(!"all".equals(name)&&name!=null) {
                p.put(name,"%"+value+"%");
            }
            List<StudentRecord> studentRecords= (List<StudentRecord>) getSelfService().list("query.studentRecord-entity",p,null);
            try(OutputStream os=response.getOutputStream()) {
                response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("学员档案.xls", "UTF-8"));
                Context context = new Context();
                context.putVar("studentRecords", studentRecords);
                JxlsHelper.getInstance().processTemplateAtCell(is, os, context, "学员档案!A1");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    @RequestMapping(value = "/studentRecord",method = RequestMethod.GET)
    public String studentRecord(){
        return "school/studentRecord/studentRecord";
    }
    @RequestMapping(value = "/studentRecord",method = RequestMethod.POST)
    @ResponseBody()
    public Object studentRecord(int page,int rows,String name,String value){

        Pagination pagination=new Pagination();
        pagination.setIndex(page);
        pagination.setSize(rows);
        Map condition=new HashMap();
        condition.put(Pagination.TRANSFORMER, Transformers.ALIAS_TO_ENTITY_MAP);
        condition.put(Pagination.RESULT_HQL,"query.studentRecord");
        Map p=new HashMap();
        if(!"all".equals(name)&&name!=null) {
            p.put(name,"%"+value+"%");
        }
        condition.put(Pagination.PARAMS,p);
        pagination.setCondition(condition);
        getSelfService().browse(pagination);
        Map map=new HashMap();
        map.put("total",pagination.getTotal());
        map.put("rows",pagination.getResult());
        return map;
    }
}
